package com.kanshu.ksgb.fastread.doudou.module.book.presenter;

import android.text.TextUtils;

import com.kanshu.ksgb.fastread.doudou.app.Xutils;
import com.kanshu.ksgb.fastread.doudou.base.basemvp.BaseMvpPresenter;
import com.kanshu.ksgb.fastread.doudou.base.basemvp.IGenrialMvpView;
import com.kanshu.ksgb.fastread.doudou.common.net.INetCommCallback;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult;
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.RetrofitHelper;
import com.kanshu.ksgb.fastread.doudou.common.net.rx.BaseObserver;
import com.kanshu.ksgb.fastread.doudou.common.util.NetUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.BookInfo;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.ChapterBean;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.DeleteBookBean;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.ShakeBean;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.SimpleChapterBean;
import com.kanshu.ksgb.fastread.doudou.common.business.event.ShelfEvent;
import com.kanshu.ksgb.fastread.doudou.module.reader.utils.SettingManager;
import com.kanshu.ksgb.fastread.doudou.module.book.retrofit.BookService;
import com.kanshu.ksgb.fastread.doudou.module.book.retrofit.requestparams.BookPageParams;
import com.kanshu.ksgb.fastread.doudou.module.book.retrofit.requestparams.ChapterRequestParams;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.subjects.Subject;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;

/**
 * Created by wcy on 2017\7\4 0004.
 */

public class BookPresenter extends BaseMvpPresenter {
    BookModel mBookModel = new BookModel();
    IGenrialMvpView<BaseResult<List<ChapterBean>>> mChapterListView;
    IGenrialMvpView<BaseResult<List<BookInfo>>> mBookLikeListView;
    IGenrialMvpView<BaseResult<List<BookInfo>>> mShakeBookListView;
    IChapterView mChapterView;
    BookService mBookService;
    List<Disposable> mDisposables = new ArrayList<>();
    List<Call> mCalls = new ArrayList<>();

    public BookPresenter(Subject<Integer> lifeCyclerSubject) {
        super(lifeCyclerSubject);
        RetrofitHelper helper = RetrofitHelper.getInstance();
        mBookService = helper.createService(BookService.class);
    }

    public void setChapterListView(IGenrialMvpView<BaseResult<List<ChapterBean>>> v) {
        mChapterListView = v;
    }

    public void setChapterView(IChapterView v) {
        mChapterView = v;
    }

    public void setBookLikeListView(IGenrialMvpView<BaseResult<List<BookInfo>>> v) {
        mBookLikeListView = v;
    }

    public void setShakeBookListView(IGenrialMvpView<BaseResult<List<BookInfo>>> v) {
        mShakeBookListView = v;
    }

    public void getChapterList(BookPageParams params) {
        mBookModel.getChapterList(params, new INetCommCallback<BaseResult<List<ChapterBean>>>() {
            @Override
            public void onResponse(BaseResult<List<ChapterBean>> chapterBeen) {
                if (mChapterListView != null) {
                    mChapterListView.dismissLoading();
                    mChapterListView.showContent(chapterBeen);
                }
            }

            @Override
            public void onError(int code, String errDesc) {
                if (mChapterListView != null) {
                    mChapterListView.dismissLoading();
                    mChapterListView.showError(code, errDesc);
                }
            }
        });
    }

    public void getChapterContent(ChapterRequestParams params) {
        mBookModel.getChapterContent(params, new INetCommCallback<BaseResult<ChapterBean>>() {
            @Override
            public void onResponse(BaseResult<ChapterBean> chapterBean) {
                if (mChapterView != null) {
                    mChapterView.dismissLoading();
                    mChapterView.showContent(chapterBean);
                }
            }

            @Override
            public void onError(int code, String errDesc) {
                if (mChapterView != null) {
                    mChapterView.dismissLoading();
                    mChapterView.showError(code, errDesc);
                }
            }
        });
    }

    /**
     * 根据章节order获取章节信息
     *
     * @param book_id
     * @param order
     */
    public void getSimpleChapterInfo(String book_id, String order) {
        mBookService.getSimpleChapterInfo(book_id, order)
                .compose(asyncRequest())
                .subscribe(new BaseObserver<SimpleChapterBean>() {
                    @Override
                    public void onResponse(BaseResult<SimpleChapterBean> simpleChapterBeanBaseResult, SimpleChapterBean simpleChapterBean, Disposable disposable) {
                        if (mChapterView != null) {
                            mChapterView.dismissLoading();
                            mChapterView.showSimpleChapterInfo(simpleChapterBean);
                        } else {
                            if (!TextUtils.isEmpty(order)) {
                                SettingManager.getInstance().saveSimpleChapterInfo(book_id, Integer.parseInt(order), simpleChapterBean);
                            }
                        }
                        mDisposables.add(mDisposable);
                    }

                    @Override
                    public void onError(int code, String errDesc) {
                        super.onError(code, errDesc);
                        mDisposables.add(mDisposable);
                    }
                });

    }

    @Override
    public void detachView() {
        mChapterView = null;
        mChapterListView = null;
        mBookLikeListView = null;
        mShakeBookListView = null;
        mBookModel.cancel();
        Utils.dispose(mDisposables);
        Utils.cancelCall(mCalls);
        super.detachView();
    }


    /**
     * 加入书架
     *
     * @param bookId
     */
    public void joinBookShelf(String bookId) {
        if (!NetUtils.isNetworkAvailable(Xutils.getContext())) {
            ShelfEvent event = new ShelfEvent(ShelfEvent.ADD_TO_SHELF_FAIL);
            EventBus.getDefault().post(event);
            return;
        }
        mBookService.joinBookShelf(bookId)
                .compose(asyncRequest())
                .subscribe(new BaseObserver<BookInfo>() {

                    @Override
                    public void onError(int code, String errDesc) {
                        super.onError(code, errDesc);
                        if (mDisposable.isDisposed()) {
                            return;
                        }
                        mDisposables.add(mDisposable);
                        ShelfEvent event = new ShelfEvent(ShelfEvent.ADD_TO_SHELF_FAIL);
                        EventBus.getDefault().post(event);
                    }

                    @Override
                    public void onResponse(BaseResult<BookInfo> info, BookInfo bookInfo, Disposable disposable) {
                        if (mDisposable.isDisposed()) {
                            return;
                        }
                        mDisposables.add(disposable);
                        if (BaseResult.isNotNull(info)) {
                            if (bookInfo == null) {
                                ShelfEvent event = new ShelfEvent(ShelfEvent.ADD_TO_SHELF_FAIL);
                                EventBus.getDefault().post(event);
                            } else {
                                ShelfEvent event = new ShelfEvent(ShelfEvent.ADD_TO_SHELF_SUCCESS);
                                event.obj = bookInfo;
                                EventBus.getDefault().post(event);
                            }
                        }
                    }
                });
    }

    /**
     * 书从书架中删除(3.0)
     *
     * @param bookId
     */
    public void delFromBookShelf(String bookId) {
        if (!NetUtils.isNetworkAvailable(Xutils.getContext())) {
            ShelfEvent event = new ShelfEvent(ShelfEvent.DEL_FROM_SHELF_FAIL);
            EventBus.getDefault().post(event);
            return;
        }
        mBookService.delFromBookShelf(bookId)
                .compose(asyncRequest())
                .subscribe(new BaseObserver<DeleteBookBean>() {
                    @Override
                    public void onResponse(BaseResult<DeleteBookBean> deleteBookBeanBaseResult, DeleteBookBean deleteBookBean, Disposable disposable) {
                        if (deleteBookBean != null && !Utils.isEmptyList(deleteBookBean.book_ids)) {
                            ShelfEvent event = new ShelfEvent(ShelfEvent.DEL_FROM_SHELF_SUCCESS);
                            event.obj = deleteBookBean.book_ids;
                            EventBus.getDefault().post(event);
                        } else {
                            ShelfEvent event = new ShelfEvent(ShelfEvent.DEL_FROM_SHELF_FAIL);
                            EventBus.getDefault().post(event);
                        }
                    }

                    @Override
                    public void onError(int code, String errDesc) {
                        super.onError(code, errDesc);
                        ShelfEvent event = new ShelfEvent(ShelfEvent.DEL_FROM_SHELF_FAIL);
                        EventBus.getDefault().post(event);
                    }
                });
    }


    /**
     * 阅读器尾页-猜你喜欢
     *
     * @param category_id_1 一级分类ID
     */
    public void getBookLike(String category_id_1) {
        mBookService.getBookLike(category_id_1)
                .compose(asyncRequest())
                .subscribe(new BaseObserver<List<BookInfo>>() {
                    @Override
                    public void onResponse(BaseResult<List<BookInfo>> listBaseResult, List<BookInfo> bookInfo, Disposable disposable) {
                        if (mBookLikeListView != null) {
                            mBookLikeListView.dismissLoading();
                            mBookLikeListView.showContent(listBaseResult);
                        }
                        mDisposables.add(mDisposable);
                    }

                    @Override
                    public void onError(int code, String errDesc) {
                        super.onError(code, errDesc);
                        if (mDisposable.isDisposed()) {
                            return;
                        }
                        mDisposables.add(mDisposable);
                    }
                });
    }

    /**
     * 摇一摇
     *
     * @param type_name 固定值为: yaoyiyao
     * @param sex       性别： 0 保密， 1男， 2女
     */
    public void getShakeBook(String type_name, String sex) {
        mBookService.getShakeBook(type_name, sex)
                .compose(asyncRequest())
                .subscribe(new BaseObserver<List<BookInfo>>() {
                    @Override
                    public void onResponse(BaseResult<List<BookInfo>> listBaseResult, List<BookInfo> bookInfos, Disposable disposable) {
                        if (mShakeBookListView != null) {
                            mShakeBookListView.dismissLoading();
                            mShakeBookListView.showContent(listBaseResult);
                        }
                        mDisposables.add(mDisposable);
                    }

                    @Override
                    public void onError(int code, String errDesc) {
                        super.onError(code, errDesc);
                        if (mDisposable.isDisposed()) {
                            return;
                        }
                        mDisposables.add(mDisposable);
                    }
                });
    }

    /**
     * 更新书籍通知-查询
     *
     * @param bookId 书籍id
     */
    public void queryUpdateBook(String bookId, BaseObserver<ShakeBean> observer) {
        mBookService.queryUpdateBook(bookId)
                .compose(asyncRequest())
                .subscribe(observer);
    }

    /**
     * 更新书籍通知-添加
     *
     * @param bookId   书籍id
     * @param callback 回调
     */
    public void addBookUpdate(String bookId, Callback<ResponseBody> callback) {
        mBookService.addBookUpdate(bookId).enqueue(callback);
    }

    /**
     * 更新书籍通知-删除
     *
     * @param bookId   书籍id
     * @param callback 回调
     */
    public void delBookUpdate(String bookId, Callback<ResponseBody> callback) {
        mBookService.delBookUpdate(bookId).enqueue(callback);
    }
}
